define(function (require, exports, module) {
    var angular = require('angular');
    require("pagination");
    require("angular-ui");
    require("/public/js/plugins/select2/select2");
    require('/public/js/myservice/contract/contract-common');
    require("uploader");
    var dialog = require("dialogplus");
    var util = require("util");
    var api_prefix = G_CONFIG["api_prefix"]; //api前缀
    var ui = require("ui");
    var config = require('/public/js/myservice/config');

    angular.module('ContractDocs', [])
        .controller('contractDocsCtrl', ['$scope', '$routeParams', 'contractCommonService', function ($scope, $routeParams, contractCommonService) {

            $scope.contractTypeName = $routeParams.contractType;

            //合同信息
            $scope.contractBaseInfo = {customer_property: 0, contract_status: 0};
            $scope.contractDocsInfo = [];
            $scope.contractFiles = [];

            //产品列表
            var contractId = $routeParams.id;
            if (contractId) {
                //编辑模式先设为只读（复核状态），避免复核的合同先显示编辑按钮再隐藏导致的刷新
                $scope.contractBaseInfo.contract_status = 1;
            }

            //获取合同信息
            $scope.loadContract = function (contractId) {
                if (contractId) {
                    //合同基本信息
                    contractCommonService.getContract(contractId, function (data) {
                        $scope.contractBaseInfo = data.contract;
                        $scope.$applyAsync();
                    });

                    //合同文档信息
                    var url = api_prefix + 'contract/get-contract-documents';
                    $.ajax({
                        url: url,
                        type: 'post',
                        dataType: 'json',
                        data: {contractId: contractId},
                        success: function (res) {
                            if (res.retCode === "0") {
                                var data = res.data;
                                $scope.contractDocsInfo = data.contractDocuments;
                                $scope.contractFiles = data.file;
                                $scope.$applyAsync();
                            } else {
                                util.alert(res.errMsg);
                            }
                        },
                        error: function () {
                            util.alert('系统维护，请稍候重试！');
                        }
                    });
                }
            };

            //下拉框设置
            //文件类型
            $scope.ddlConfigDocumentExtName = {
                allowClear: false,
                data: [{id: '合同', text: '合同'}, {id: '标的物', text: '标的物'}, {id: '主体协议', text: '主体协议'}, {
                    id: '补充协议',
                    text: '补充协议'
                }, {
                    id: '战略协议',
                    text: '战略协议'
                }],
                minimumResultsForSearch: 'Infinity'
            };

            //文档类型
            $scope.ddlConfigDocumentType = {
                allowClear: false,
                data: [{id: '复印件', text: '复印件'}, {id: '原件', text: '原件'}],
                minimumResultsForSearch: 'Infinity'
            };

            //纸质合同类型
            $scope.ddlConfigContractDocumentType = {
                allowClear: false,
                data: [{id: '云链租赁合同', text: '云链租赁合同'}],
                minimumResultsForSearch: 'Infinity'
            };

            //纸质合同存放位置
            $scope.ddlConfigDocumentPath = {
                allowClear: false,
                data: [
                    {id: '柜1上', text: '柜1上'},
                    {id: '柜1中', text: '柜1中'},
                    {id: '柜1下', text: '柜1下'},
                    {id: '柜2上', text: '柜2上'},
                    {id: '柜2中', text: '柜2中'},
                    {id: '柜2下', text: '柜2下'},
                    {id: '柜3上', text: '柜3上'},
                    {id: '柜3中', text: '柜3中'},
                    {id: '柜3下', text: '柜3下'},
                    {id: '柜4上', text: '柜4上'},
                    {id: '柜4中', text: '柜4中'},
                    {id: '柜4下', text: '柜4下'},
                    {id: '柜5上', text: '柜5上'},
                    {id: '柜5中', text: '柜5中'},
                    {id: '柜5下', text: '柜5下'},
                    {id: '柜6上', text: '柜6上'},
                    {id: '柜6中', text: '柜6中'},
                    {id: '柜6下', text: '柜6下'},
                    {id: '柜7上', text: '柜7上'},
                    {id: '柜7中', text: '柜7中'},
                    {id: '柜7下', text: '柜7下'},
                    {id: '柜8上', text: '柜8上'},
                    {id: '柜8中', text: '柜8中'},
                    {id: '柜8下', text: '柜8下'}
                ],
                minimumResultsForSearch: 'Infinity'
            };

            //保管人
            $scope.ddlConfigKeeper = {
                allowClear: false,
                ajax: {
                    url: api_prefix + "erp-interface/get-users",
                    dataType: 'json',
                    delay: 250,
                    data: function (term) {
                        return {
                            keyword: term,
                            limit: 10
                        };
                    },
                    results: function (json, page) {
                        var data = [];
                        if (json.retCode === "0") {
                            data = json.data;
                        }
                        return {results: data};
                    },
                    processResults: function (data, page) {
                        return {
                            results: data.items
                        };
                    },
                    cache: true
                },
                escapeMarkup: function (markup) {
                    return markup;
                }, // let our custom formatter work
                minimumInputLength: 1,
                onchange2: function (newVal, scope) {
                    if (scope) {
                        scope.keeper_name = newVal.text;
                    }
                }
            };

            /**
             * 新增合同
             */
            $scope.addDocument = function () {
                var item = {
                    editMode: 1,
                    __type: 'add',
                    //contract_document_type: '云链租赁合同',
                    keeper: 'a9ca5c48-8a46-e611-bb66-848f69dfab18',
                    keeper_name:'张嘉丽',
                    pigeonhole_date: $scope.getCurrentDateTime()
                };
                $scope.contractDocsInfo.push(item);

                setTimeout(function () {
                    $('.idKeeper:last').data('select2').updateSelection({text: '张嘉丽'});
                }, 0);
            };

            $scope.getCurrentDateTime = function(){
                var date = new Date();//当前时间
                var month = zeroFill(date.getMonth() + 1);//月
                var day = zeroFill(date.getDate());//日
                var hour = zeroFill(date.getHours());//时
                var minute = zeroFill(date.getMinutes());//分
                var second = zeroFill(date.getSeconds());//秒

                //当前时间
                var curTime = date.getFullYear() + "-" + month + "-" + day  + " " + hour + ":" + minute + ":" + second;

                return curTime;
            }

            function zeroFill(i){
                if (i >= 0 && i <= 9) {
                    return "0" + i;
                } else {
                    return i;
                }
            }

            /**
             * 修改业绩
             * @type {number}
             */
            $scope.editContractDocument = function (item, idx) {
                //先保存原始数据
                item.orginalData = angular.copy(item);
                item.editMode = 2;

                //获取当前修改的人物下拉框
                var items = $scope.contractDocsInfo;
                var n = -2;
                var it;
                for (var i = idx; it = items[i]; i--) {
                    if (it.editMode == 1 || it.editMode == 2) {
                        //每点开一个，会生成2个相同class的元素
                        n += 2;
                    }
                }
                setTimeout(function () {
                    $(".idKeeper").eq(n).select2("data", {
                        id: item.document_id,
                        text: item.keeper_name
                    });
                    $scope.$applyAsync();
                }, 0)

            };

            /**
             * 删除收入
             *
             */
            $scope.delContractDocument = function (item) {
                util.confirm('确定要删除此文档吗？', {
                    ok: function () {
                        angular.extend(item, {__type: 'delete', editMode: 3});
                        $scope.$applyAsync();
                    }
                });
            };

            /**
             * 保存收入信息
             * @type {number}
             */
            $scope.saveContractDocument = function (item) {
                if (!item.document_ext_name) {
                    util.alert('文件类型不能为空！');
                    return;
                }

                if (!item.document_type) {
                    util.alert('文档类型不能为空！');
                    return;
                }

                if (!item.pigeonhole_date) {
                    util.alert('纸质合同归档日期不能为空！');
                    return;
                }

                if (!item.document_path) {
                    util.alert('纸质合同存放位置不能为空！');
                    return;
                } else if (item.document_path.length > 20) {
                    util.alert('纸质合同存放位置不能大于20字符');
                    return false
                }

                //if (!item.contract_document_type) {
                //    util.alert('纸质合同类型不能为空！');
                //    return;
                //}

                if (!item.keeper) {
                    util.alert('保管人不能为空！');
                    return;
                }

                if (!item.document_dir) {
                    util.alert('所属文件夹名称不能为空！');
                    return;
                } else if (item.document_dir.length > 20) {
                    util.alert('所属文件夹名称不能大于20字符');
                    return false
                }

                item.editMode = 0;
                item.orginalData = '';
                $scope.$applyAsync();
            };

            /**
             * 取消保存
             * @type {number}
             */
            $scope.cancelContractDocument = function (item, idx) {
                if (item.editMode == 1) {
                    $scope.contractDocsInfo.splice(idx, 1);
                } else {
                    angular.extend(item, item.orginalData);
                    item.editMode = 0;
                    item.orginalData = '';
                }
            };

            //能否保存判断
            $scope.saveEnabled = function () {
                var docs = $scope.contractDocsInfo;
                var n = 0;
                $.grep(docs, function (d, i) {
                    if (d.editMode == 1 || d.editMode == 2) {
                        n++;
                    }
                });
                return n;
            };

            /**
             * 保存信息
             */
            $scope.save = function () {
                var url = api_prefix + 'contract/save-contract-documents';
                var data = {
                    contractId: contractId,
                    documents: $scope.contractDocsInfo,
                    files: $scope.contractFiles
                };
                $.ajax({
                    url: url,
                    type: 'post',
                    dataType: 'json',
                    data: data,
                    success: function (res) {
                        if (res.retCode === "0") {
                            util.alert('保存成功');
                            $scope.loadContract(contractId);
                        } else {
                            util.alert(res.errMsg);
                        }
                    },
                    error: function () {
                        util.alert('系统维护，请稍候重试！');
                    }
                });
            };

            $scope.exportCaibaoDetail = function(){
                util.confirm('确定下载釆宝明细吗？', {
                    ok: function () {
                        var parms = {contractid: contractId};
                        var url = api_prefix + '/contract/export-contract-caibao-detail';
                        util.download(url, parms);
                    }
                });
            }

            //附件上传初始化
            $('#fileupload').fileupload({
                dataType: 'json',
                url: api_prefix + "/common/file/upload-document&XDEBUG_SESSION_START=netbeans-xdebug",
                add: function (e, data) {
                    // 大小限制
                    if (data.files.length > 0) {
                        if (data.files[0].size > config.uploader.max_file_size) {
                            util.alert('文件大小超出' + config.uploader.max_file_size_text + '，无法上传。');
                            return;
                        }
                    }
                    data.submit();
                    ui.loading('', '正在上传…');
                },
                done: function (e, data) {
                    var res = data.result;
                    if (res.retCode == "0") {
                        var document = {
                            __type: 'add',
                            document_id: data._time,
                            document_name: data.files[0].name,
                            document_ext_name: '',
                            document_path: res.data.path,
                            business_id: ''
                        };
                        $scope.contractFiles.push(document);
                        $scope.$applyAsync();
                        ui.removeLoading();

                        $("#fileupload_error").html("");
                        $("#fileupload_error").hide();
                    } else {
                        ui.removeLoading();
                        $("#fileupload_error").html("上传失败:" + res.errMsg);
                        $("#fileupload_error").show();
                    }
                },
                fail: function (e, data) {
                    $("#fileupload_error").html("上传失败:" + data.errorThrown);
                    $("#fileupload_error").show();
                    ui.removeLoading();
                },
                always: function (e, data) {
                    ui.removeLoading();
                }
            });

            /**
             * 删除附件
             * @param data
             * @param id
             */
            $scope.delAttachment = function (item, idx) {
                if (item.__type == 'add') {
                    $scope.contractFiles.splice(idx, 1);
                } else {
                    angular.extend(item, {__type: 'delete'});
                }
                $scope.$applyAsync();
            };

            //页面初始化
            $scope.init = function () {
                $scope.loadContract(contractId);
            };
            $scope.init();
        }]);
});